<template>
  <div class="page-container">
    <page-form :model="form" ref="formRef" layout="vertical">
      <card title="车辆信息">
        <car-info-block
          v-if="defaultCarId"
          :carInfo="carInfo"
          :fieldList="[
            { label: '车架号', prop: 'vin' },
            { label: '车辆当前归属门店', prop: 'siteName' },
            { label: '归属车场', prop: 'libraryName' },
          ]"
        />
        <page-form-row v-else>
          <page-form-item field="carId" label="车牌号" required :rules="{ required: true, message: '请选择车牌号' }">
            <remote-select
              v-model="form.carId"
              type="car_licenseno_list"
              :params="{
                idList: [defaultCarId],
              }"
              @change="changeCarFn"
            />
          </page-form-item>
          <page-form-item label="车架号">
            <i-input disabled :model-value="carInfo?.vin" />
          </page-form-item>
          <page-form-item label="车型">
            <i-input disabled placeholder="请选择" :model-value="carInfo?.modelName" icon="down" />
          </page-form-item>
          <page-form-item label="车辆当前归属门店">
            <i-input disabled placeholder="请选择" :model-value="carInfo?.siteName" icon="down" />
          </page-form-item>
          <page-form-item label="归属车库">
            <i-input disabled placeholder="请选择" :model-value="carInfo?.libraryName" icon="down" />
          </page-form-item>
        </page-form-row>
      </card>
      <card title="交强保险单">
        <div class="empty-custom-fee flex" v-if="form.compulsory.length == 0">
          <div class="empty-custom-fee-content">
            <a-empty description="暂无交强保险单" />
            <a-button type="primary" @click="addInsureFn('compulsory')">
              <template #icon>
                <icon-plus />
              </template>
              新增交强保险单
            </a-button>
          </div>
        </div>
        <compulsory operateType="addInsure" v-else />
      </card>
      <card title="商业保险单" :showDivider="false">
        <div class="empty-custom-fee flex" v-if="form.business.length == 0">
          <div class="empty-custom-fee-content">
            <a-empty description="暂无商业保险单" />
            <a-button type="primary" @click="addInsureFn('business')">
              <template #icon>
                <icon-plus />
              </template>
              新增商业保险单
            </a-button>
          </div>
        </div>
        <business operateType="addInsure" v-else />
      </card>
    </page-form>
  </div>
  <page-form-footer @ok="submitFn" :ok-loading="okLoading" />
</template>

<script setup name="CarInsureForm">
  import { ref, provide, computed } from 'vue'
  import { useRoute } from 'vue-router'
  import { insertInsure } from '@/api/asset/carInsure.js'
  import { getCarDetail } from '@/api/asset/car'
  import { Modal, Message } from '@arco-design/web-vue'
  import useNavigate from '@/hooks/useNavigate'
  import compulsory from '@/views/assets/operation/car-insure/components/insurance-policy/compulsory.vue'
  import business from '@/views/assets/operation/car-insure/components/insurance-policy/business.vue'
  import dayjs from 'dayjs'

  const { navigateBack } = useNavigate()
  const route = useRoute()

  const props = defineProps({
    carId: [String, Number],
  })

  // 默认的车辆id
  const defaultCarId = computed(() => {
    let carId = route.query.carId
    let propCarId = props.carId
    return carId || propCarId
  })
  if (defaultCarId.value) {
    getCarDetail({ id: defaultCarId.value }).then(({ result }) => {
      carInfo.value = result
    })
  }
  const carInfo = ref()
  const changeCarFn = (_, option = {}) => {
    carInfo.value = option
    changeInsureFn()
  }
  const form = ref({
    compulsory: [],
    business: [],
    // 初始化接口传参
    carId: defaultCarId.value,
  })
  provide('form', form)
  provide('carInfo', carInfo)
  // 新增保险单
  const addInsureFn = (type) => {
    if (type == 'compulsory') {
      form.value.compulsory.push({
        insureKind: 0,
        siteId: carInfo.value?.siteId,
        siteName: carInfo.value?.siteName,
      })
    }
    if (type == 'business') {
      form.value.business.push({
        insureKind: 1,
        siteId: carInfo.value?.siteId,
        siteName: carInfo.value?.siteName,
        carInsureDetail: [{}],
      })
    }
  }
  const changeInsureFn = () => {
    form.value.compulsory.forEach((item, index) => {
      item.siteId = carInfo.value?.siteId
      item.siteName = carInfo.value?.siteName
      formRef.value.validateField(`compulsory.${index}.siteId`)
    })
    form.value.business.forEach((item, index) => {
      item.siteId = carInfo.value?.siteId
      item.siteName = carInfo.value?.siteName
      formRef.value.validateField(`business.${index}.siteId`)
    })
  }
  const formRef = ref()
  // 校验保险结束日期是否大于开始日期
  const checkEndDate = (insureList) => {
    return new Promise((resolve) => {
      // 车辆的保单到期日
      const { compulsoryEndDate, businessEndDate } = carInfo.value
      // 保单信息
      // 交强险
      const compulsoryInsure = insureList.find((item) => item.insureKind == 0)
      // 商业险
      const businessInsure = insureList.find((item) => item.insureKind == 1)

      // 保单是否早于车辆保单
      const insureIsBeforeCar = {
        compulsory: false,
        business: false,
      }
      // 存在交强险
      if (compulsoryInsure) {
        const endDate = compulsoryInsure.endDate
        if (compulsoryEndDate && dayjs(endDate).isBefore(compulsoryEndDate)) {
          insureIsBeforeCar.compulsory = true
        }
      }
      // 存在商业险
      if (businessInsure) {
        const endDate = businessInsure.endDate
        if (businessEndDate && dayjs(endDate).isBefore(businessEndDate)) {
          insureIsBeforeCar.business = true
        }
      }
      // 存在交强险或者商业险早于车辆保单
      if (insureIsBeforeCar.compulsory || insureIsBeforeCar.business) {
        let tips = ''
        if (insureIsBeforeCar.compulsory && insureIsBeforeCar.business) {
          tips = '当前交强险、商业险保单的到期日早于车辆上的交强险、商业险到期日，请确认是否新增？' 
        } else {
          if (insureIsBeforeCar.compulsory) {
            tips = '当前交强险保单的到期日早于车辆上的交强险到期日，请确认是否新增？'
          } else {
            tips = '当前商业险保单的到期日早于车辆上的商业险到期日，请确认是否新增？'
          }
        }
        Modal.confirm({
          title: '提示',
          okText: '确认',
          content: tips,
          onOk: () => {
            resolve()
          },
        })
      } else {
        resolve()
      }
    })
  }
  const okLoading = ref(false)
  const submitFn = (noticeSuccess) => {
    formRef.value.validate((error) => {
      if (!error) {
        const param = {
          ...form.value,
        }
        // 未录入保险信息
        if (form.value.compulsory.length == 0 && form.value.business.length == 0) {
          Message.warning('请添加保险')
          return false
        }
        // 处理保险 start
        let compulsory = param.compulsory
        // 商业险处理投保信息 （底部金额表格信息）
        let business = JSON.parse(JSON.stringify(param.business))
        business.forEach((item) => {
          let carInsureDetail = item.carInsureDetail
          if (carInsureDetail.length > 0) {
            for (var i = 0; i < carInsureDetail.length; i++) {
              var item2 = carInsureDetail[i]
              if (Object.keys(item2).length == 0) {
                carInsureDetail.splice(i, 1)
                i--
              }
            }
          }
        })
        param.insureAddList = [...compulsory, ...business]
        delete param.compulsory
        delete param.business
        // 处理保险 end
        checkEndDate(param.insureAddList).then(() => {
          // insertInsure
          okLoading.value = true
          insertInsure(param)
            .then(() => {
              noticeSuccess()
              navigateBack()
            })
            .finally(() => {
              okLoading.value = false
            })
        })
      }
    })
  }
</script>

<style lang="less" scoped>
  .empty-custom-fee {
    margin: 30px 0 35px;
    justify-content: center;
    :deep(.arco-empty) {
      .arco-empty-description {
        color: #d8d8d8;
        font-size: 12px;
      }
      .arco-icon {
        color: #d8d8d8;
      }
    }
  }
</style>
